import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:platform_service/platform_service.dart';
import 'dart:ui' as ui;

class ImagePickerExample extends StatefulWidget {
  const ImagePickerExample({Key? key}) : super(key: key);

  static Future push(BuildContext context) =>
      Navigator.of(context).push(PageRouteBuilder(
        settings: const RouteSettings(name: 'ImagePickerExample'),
        pageBuilder: (context, animation, secondaryAnimation) =>
            const ImagePickerExample(),
      ));

  @override
  State<ImagePickerExample> createState() => _ImagePickerExampleState();
}

class _ImagePickerExampleState extends State<ImagePickerExample> {
  var _showLoading = false;
  List<NDFileInfo> _fileList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ImagePickerDemo'),
      ),
      body: Column(
        children: <Widget>[
          const SizedBox(height: 16),
          ElevatedButton(
            child: const Text('相册选择图片'),
            onPressed: () {
              PlatformService.pickImages(
                maxCount: 8,
                enableCamera: false,
              ).then((results) {
                if (results.isNotEmpty) {
                  _fileList = results;
                }
                setState(() {});
              }).catchError((err) {
                debugPrint('err:${err.toString()}');
                return <NDFileInfo>[];
              });
            },
          ),
          const SizedBox(height: 12),
          ElevatedButton(
            child: const Text('相册选择图片(带水印)'),
            onPressed: () {
              setState(() {
                _showLoading = true;
              });
              PlatformService.pickImages(
                  maxCount: 8,
                  enableCamera: false,
                  isWaterMark: true,
                  isWaterMarkTiled: true,
                  waterMarkSettings: [
                    ImageWaterMarkSettingModel(
                        text: '水印',
                        radians: 0.25,
                        textStyle: ui.TextStyle(
                            fontSize: 40,
                            color: const Color.fromRGBO(102, 102, 102, 0.5))),
                  ]).then((results) {
                if (results.isNotEmpty) {
                  _fileList = results;
                }
                setState(() {
                  _showLoading = false;
                });
              }).catchError((err) {
                debugPrint('err:${err.toString()}');
                setState(() {
                  _showLoading = false;
                });
                return <NDFileInfo>[];
              });
            },
          ),
          ElevatedButton(
            child: const Text('拍照（带水印）'),
            onPressed: () {
              setState(() {
                _showLoading = true;
              });
              PlatformService.takePicture(
                  isWaterMark: true,
                  isWaterMarkTiled: true,
                  waterMarkSettings: [
                    ImageWaterMarkSettingModel(
                        text: '水印',
                        textStyle: ui.TextStyle(
                            fontSize: 40,
                            color: const Color.fromRGBO(102, 102, 102, 0.5))),
                  ]).then((res) {
                if (res != null) {
                  _fileList.clear();
                  _fileList.add(res);
                }
                setState(() {
                  _showLoading = false;
                });
              }).catchError((err) {
                setState(() {
                  _showLoading = false;
                });
                debugPrint('err:${err.toString()}');
                return null;
              });
            },
          ),
          if (_showLoading)
            Column(
              children: const [
                SizedBox(height: 12),
                Text('水印添加中，请耐心等待~~~'),
                SizedBox(height: 12),
                CircularProgressIndicator(
                  color: Colors.redAccent,
                  strokeWidth: 2,
                ),
              ],
            ),
          Expanded(
              child: ListView.separated(
                  itemBuilder: (context, index) {
                    var file = _fileList[index];
                    return Column(
                      children: [
                        const SizedBox(height: 8),
                        Text(file.name),
                        const SizedBox(height: 8),
                        file.path != null
                            ? Image.file(
                                File.fromUri(Uri.file(file.path ?? '')),
                                width: 400,
                                height: 400,
                              )
                            : Image.memory(
                                Uint8List.fromList(file.fileBytes ?? []),
                                width: 400,
                                height: 400,
                              )
                      ],
                    );
                  },
                  separatorBuilder: (context, index) =>
                      const Divider(height: 1, color: Colors.grey),
                  itemCount: _fileList.length))
        ],
      ),
    );
  }
}
